package com.wing.qualityTesting.controller.admin;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wing.common.enums.Idempotent;
import com.wing.productionPlan.model.response.QualityTestingRecordDetailVO;
import com.wing.productionPlan.service.QualityTestingRecordDetailService;
import com.wing.qualityTesting.model.entity.QualityTestingRecordValue;
import com.wing.qualityTesting.model.response.ProcessQualityVO;
import com.wing.qualityTesting.model.response.QualityTestingRecordVO;
import com.wing.qualityTesting.model.response.WorkOrderQualityTestingTaskVO;
import com.wing.qualityTesting.service.QualityTestingRecordValueService;
import com.wing.web.annotation.RequestObjectFieldIgnore;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.PageResult;
import com.wing.qualityTesting.model.entity.QualityTestingRecord;
import com.wing.qualityTesting.model.request.QualityTestingRecordForm;
import com.wing.qualityTesting.service.QualityTestingRecordService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * @author
 */
@Slf4j
@Validated
@Api(value = "Admin-质检记录表管理", tags = "#/qualityTesting/qualityTestingRecord")
@RestController("qualityTestingRecordController")
@RequestMapping("qualityTesting/admin/qualityTestingRecord")
@RequiredArgsConstructor
public class QualityTestingRecordController {

    private final QualityTestingRecordService qualityTestingRecordService;
    private final QualityTestingRecordDetailService qualityTestingRecordDetailService;
    private final QualityTestingRecordValueService qualityTestingRecordValueService;

    @ApiOperation(value = "查询所有质检记录表", notes = "搜索")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "第几页", defaultValue = "1", example = "1", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "limit", value = "每页多少条", defaultValue = "10", example = "10", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "sort", value="排序字段名", defaultValue = "create_time", example = "create_time", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "order", value="排序规则(asc:正序, desc:倒序)", defaultValue = "asc", example = "asc", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "processId", value="工序id", dataType = "Long", paramType = "query")
            ,@ApiImplicitParam(name = "code", value="质检记录编号", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "workOrderCode", value="工单编号", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "inspectionPeople", value="送检人", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "creatorName", value="检验员", dataType = "String", paramType = "query")
    })
    @GetMapping("/list")
    public PageResult<QualityTestingRecordVO> list(
            @RequestParam(defaultValue = "1") Integer page
            ,@RequestParam(defaultValue = "10") Integer limit
            ,@RequestParam(defaultValue = "create_time") String sort
            ,@RequestParam(defaultValue = "asc") String order
            ,Long processId
            ,String code
            ,String workOrderCode
            ,String inspectionPeople
            ,String creatorName
    ){

        Page<QualityTestingRecord> pg = new Page<>(page, limit);
        Map paramMap = new HashMap();
        if(processId != null){
            paramMap.put("processId",processId);
        }
        if(StringUtils.isNotBlank(code)){
            paramMap.put("code",code);
        }
        if(StringUtils.isNotBlank(workOrderCode)){
            paramMap.put("workOrderCode",workOrderCode);
        }
        if(StringUtils.isNotBlank(inspectionPeople)){
            paramMap.put("inspectionPeople",inspectionPeople);
        }
        if(StringUtils.isNotBlank(creatorName)){
            paramMap.put("creatorName",creatorName);
        }
        //搜索

        IPage<QualityTestingRecordVO> list = qualityTestingRecordService.pageList4app(pg,paramMap);
        for (QualityTestingRecordVO item : list.getRecords()){
            //计算合格率
            if(item.getQualifiedQuantity()!=null && item.getSubmissionQuantity()!=null) {
                int passRate = (int) ((new BigDecimal((float) item.getQualifiedQuantity() / item.getSubmissionQuantity())
                        .setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue()) * 100);
                item.setPassRate(passRate + "%");
            }
        }
        return new PageResult<>(list.getRecords(), list.getTotal());
    }

    @ApiOperation(value = "添加质检记录表", notes = "添加")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/add")
    @Idempotent(keyPrefix = "qualityTestingRecordAdd")
    public JsonResult add(@Validated(QualityTestingRecordForm.Add.class) QualityTestingRecordForm qualityTestingRecordForm) {
        if (qualityTestingRecordService.add(qualityTestingRecordForm) > 0) {
            return JsonResult.success("添加成功");
        }
        return JsonResult.fail("添加失败");
    }
    @ApiOperation(value = "提交质检记录", notes = "添加")
    @PostMapping("/submitTestingRecord")
    @Idempotent(keyPrefix = "qualityTestingRecordSubmit")

    public JsonResult submitTestingRecord(@RequestBody QualityTestingRecordForm qualityTestingRecordForm) {
        try {
            qualityTestingRecordService.submitTestingRecord(qualityTestingRecordForm);
            return JsonResult.success("操作成功");
        }catch (Exception e){
            log.error("提交质检记录接口异常，原因是：{} ", e.getMessage(), e);
            return JsonResult.fail("操作失败:" + e.getMessage());
        }
    }




    @ApiOperation(value = "修改质检记录表", notes = "修改")
    @PutMapping("/update")
    @Idempotent(keyPrefix = "qualityTestingRecordUpdate")
    public JsonResult update(@Validated(QualityTestingRecordForm.Update.class) QualityTestingRecordForm qualityTestingRecordForm) {
        QualityTestingRecord qualityTestingRecord = qualityTestingRecordService.getById(qualityTestingRecordForm.getId());
        if(qualityTestingRecord == null){
        return JsonResult.fail("修改失败！");
        }
        CopyOptions copyOptions = CopyOptions.create()
        .setEditable(QualityTestingRecord.class)
        .setIgnoreError(true)
        .setIgnoreNullValue(true);
        BeanUtil.copyProperties(qualityTestingRecordForm, qualityTestingRecord, copyOptions);
        if (qualityTestingRecordService.updateById(qualityTestingRecord)) {
            return JsonResult.success("修改成功！");
        }
        return JsonResult.fail("修改失败！");
    }

    @ApiOperation(value = "删除质检记录表", notes = "删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "qualityTestingRecordId", value = "质检记录表id", required = true, dataType = "Integer", paramType = "path")
    })
    @DeleteMapping("/{id}" )
    public JsonResult delete(@PathVariable("id") Long qualityTestingRecordId) {
        if (qualityTestingRecordService.removeById(qualityTestingRecordId)) {
            return JsonResult.success("删除成功");
        }
        return JsonResult.fail("删除失败");
    }
    @ApiOperation(value = "根据质检任务id查询开工单信息", notes = "查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "taskId", value = "质检任务id", required = true, dataType = "Integer", paramType = "path")
    })
    @GetMapping("/getTestingTaskByTaskId" )
    public JsonResult<WorkOrderQualityTestingTaskVO> getTestingTaskByTaskId(Long taskId) {
        WorkOrderQualityTestingTaskVO testingTaskVO = qualityTestingRecordService.getTestingTaskByTaskId(taskId);
        return JsonResult.success(testingTaskVO);
    }

    @ApiOperation(value = "添加检验结果需要的数据", notes = "查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "taskId", value = "质检任务id", required = true, dataType = "Integer", paramType = "path")
    })
    @GetMapping("/getInspectionResultsData" )
    public JsonResult<List<ProcessQualityVO>> getInspectionResultsData(Long taskId) {
        List<ProcessQualityVO> resultsData = qualityTestingRecordService.getInspectionResultsData(taskId);
        return JsonResult.success(resultsData);
    }


    @ApiOperation(value = "查询详情质检检验结果", notes = "查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "qualityTestingRecordId", value = "质检记录id", required = true, dataType = "Integer", paramType = "path")
    })
    @GetMapping("/getTestingTaskRecordDetail")
    public JsonResult<List<QualityTestingRecordDetailVO>> getTestingTaskRecordDetail(Long qualityTestingRecordId) {
        List<QualityTestingRecordDetailVO>  list = qualityTestingRecordDetailService.getQualityTestingRecordDetail(qualityTestingRecordId);
        list.parallelStream().forEach(k -> {
            QueryWrapper<QualityTestingRecordValue> wrapper = new QueryWrapper<>();
            wrapper.eq("testing_record_detail_id",k.getId());
            List<QualityTestingRecordValue> values = qualityTestingRecordValueService.list(wrapper);
            k.setQualityValueList(values);
        });

        return JsonResult.success(list);
    }
}
